package H02.h2.Servlet;

import H02.h2.util.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/login")
public class loginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("password");

        try(Connection conn= DBUtil.getConnection()){
            String sql="SELECT * FROM users WHERE username=? AND password=?";
            PreparedStatement pstmt =conn.prepareStatement(sql);
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            ResultSet rs=pstmt.executeQuery();
            if(rs.next()){
                HttpSession session=req.getSession();//创建会话
                session.setAttribute("username",username);//将用户名存入会话
                session.setAttribute("role",rs.getString("role"));//将用户角色存入会话
                resp.sendRedirect("course");//重定向到course页面
            }else{
                resp.sendRedirect("html/HomeWork02/h2/login.html?error=true");//如果查询结果失败，则的重定向回登录界面
            }
        }catch(Exception e){//捕获异常
            e.printStackTrace();//打印异常信息
        }
    }
}
